<template>
  <el-container>

    <el-header>
      <el-input v-model="queryInfo.loginName" @blur="getUserInfo" placeholder="搜索登录名"
                prefix-icon="el-icon-search"></el-input>
      <el-input v-model="queryInfo.trueName" @blur="getUserInfo" placeholder="搜索姓名" prefix-icon="el-icon-search"
                style="margin-left: 5px"></el-input>
      <el-button type="primary" style="margin-left: 5px" icon="el-icon-plus" @click="showAddDialog">添加</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="daorushow = true">导入</el-button>
    </el-header>

    <el-main>
      <!--操作的下拉框-->
      <el-select @change="selectChange" clearable v-if="selectedInTable.length !== 0" v-model="selected"
                 :placeholder="'已选择' + selectedInTable.length + '项'" style="margin-bottom: 25px;">

        <el-option v-for="(item,index) in optionInfo" :key="index" :value="item.desc">
          <span style="float: left">{{ item.label }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.desc }}</span>
        </el-option>

      </el-select>

      <el-table
        ref="multipleTable"
        highlight-current-row
        v-loading="loading"
        :border="true"
        :data="userInfo"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">

        <el-table-column align="center"
                         type="selection"
                         width="55">
        </el-table-column>

        <el-table-column align="center"
                         prop="username"
                         label="用户名">
        </el-table-column>

        <el-table-column align="center"
                         prop="trueName"
                         label="姓名">
        </el-table-column>

        <el-table-column align="center"
                         prop="mobile"
                         label="手机号码">
        </el-table-column>

        <el-table-column align="center"
                         prop="email"
                         label="邮箱">
        </el-table-column>

        <!-- <el-table-column align="center"
                         label="角色">
          <template slot-scope="scope">
            <span class="role" v-show="scope.row.roleId === 3">管理员</span>
            <span class="role" v-show="scope.row.roleId === 1">学生</span>
          </template>
        </el-table-column> -->

        <el-table-column align="center"
                         label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createDate }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="状态">
          <template slot-scope="scope">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </template>
        </el-table-column>

        <el-table-column align="center"
                         label="">
          <template slot-scope="scope">

            <el-button v-if="scope.row.roleId==1" type="primary" @click="getInfoEdit(scope.row)"
              >编辑</el-button
            >
            <el-button v-if="scope.row.roleId==1" type="warning" @click="showUpdateNoticeDialog(scope.row)"
              >可视化分析</el-button
            >
          </template>
        </el-table-column>

      </el-table>

      <!--分页-->
      <el-pagination style="margin-top: 25px"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNo"
                     :page-sizes="[10, 20, 30, 50]"
                     :page-size="queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

    </el-main>

    <el-dialog title="用户信息" :visible.sync="addTableVisible" width="30%" @close="resetAddForm"
               center>

      <el-form :model="addForm" :rules="addFormRules" ref="addForm">

        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input :disabled="addForm.id" v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item v-if="!addForm.id" label="密码" label-width="120px" prop="password">
          <el-input v-model="addForm.password" type="password" show-password></el-input>
        </el-form-item>

        <!-- <el-form-item label="角色" label-width="120px" prop="roleId">
          <el-select v-model="addForm.roleId" placeholder="请选择角色">
            <el-option label="学生" :value="1"></el-option>
            <el-option label="管理员" :value="3"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="真实姓名" label-width="120px" prop="trueName">
          <el-input v-model="addForm.trueName"></el-input>
        </el-form-item>
          <el-form-item prop="mobile" label-width="120px" label="手机号码">
            <el-input prefix-icon="el-icon-user" v-model="addForm.mobile" placeholder="手机号码"></el-input>
          </el-form-item>
          <el-form-item prop="email" label-width="120px" label="邮箱地址">
            <el-input prefix-icon="el-icon-user" v-model="addForm.email" placeholder="邮箱地址"></el-input>
          </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser" v-if="!addForm.id">确 定</el-button>
        <el-button type="primary" @click="editUser" v-else>确定修改</el-button>
      </div>
    </el-dialog>


    <el-dialog title="学习者能力分析" :visible.sync="kshfx" width="800px" @close="resetAddForm"
               center>
        <el-container>
            <el-row>
              <div id="leidatu" style="width: 800px;height:400px;"></div>
            </el-row>

        </el-container>

      <div slot="footer" class="dialog-footer">
      </div>
    </el-dialog>

    <el-dialog title="导入" :visible.sync="daorushow" width="30%" @close="resetAddForm"
               center>

      <el-form :model="addForm" :rules="addFormRules" >
          <el-upload
            :action="uploadUrl"
            :on-success="handleSuccess"
            :on-error="handleError"
            :headers="headers"
            :before-upload="beforeUpload"
            accept=".xlsx"
            :auto-upload="false"
            ref="uploadtm"
          >
            <el-button type="primary">点击选择文件</el-button>
              <div class="el-upload__tip text-center" slot="tip">
                <span>仅允许导入xlsx格式文件。</span>
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; vertical-align: baseline"
                  @click="importTemplate"
                  >下载模板</el-link
                >
              </div>
          </el-upload>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="daorushow = false">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
      </div>
    </el-dialog>

  </el-container>

</template>

<script>
import user from '@/api/user'
import utils from '@/utils/utils'
import { generateSign } from '@/utils/sign'
import auth from '@/api/auth'
import statistic from '@/api/statistic'

export default {
  name: 'UserManage',
  data () {
    //自定义用户名校验规则
    const validateUsername = (rule, value, callback) => {
      if(!this.addForm.id){
      auth.checkUsername(this.addForm.username).then((resp) => {
        if (resp.data) {
          callback()
        } else {
          callback(new Error('用户名已存在'))
        }
      })

      }else{

          callback()
      }
    }
    return {
      daorushow:false,
      uploadUrl: 'http://localhost:8888/excel/importExcelUser',
      kshfx:false,
      //查询用户的参数
      queryInfo: {
        'loginName': '',
        'trueName': '',
        'pageNo': 1,
        'roleId': 1,
        'pageSize': 10
      },
      //用户信息
      userInfo: [],
      //下拉选择框的数据
      optionInfo: [
        {
          'label': '启用',
          'desc': 'on'
        },
        {
          'label': '禁用',
          'desc': 'off'
        },
        {
          'label': '删除',
          'desc': 'delete'
        },
        // {
        //   'label': '编辑',
        //   'desc': 'edit'
        // }
      ],
      pieData:[],
      //下拉框所选择的数据
      selected: '',
      //被选择的表格中的行数据
      selectedInTable: [],
      //所有用户的条数
      total: 0,
      //添加用户的对话框是否显示
      addTableVisible: false,
      //添加用户的表单信息
      addForm: {
        'id':'',
        'username': '',
        'password': '',
        'roleId': '',
        'trueName': '',
        'email': '',
        'mobile': ''
      },
      //添加用户表单的验证规则
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入登录用户名',
            trigger: 'blur'
          },
          {
            validator: validateUsername,
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 5,
            message: '密码必须5位以上',
            trigger: 'blur'
          }
        ],
        trueName: [
          {
            required: true,
            message: '请输入用户真实姓名',
            trigger: 'blur'
          },
        ],
        roleId: [
          {
            required: true,
            message: '请选择用户权限',
            trigger: 'blur'
          },
        ],
      },
      //表格信息加载
      loading: true,
      // 添加雷达图数据
      radarData: {
      }
    }
  },
  computed: {
    //监测头部信息的token变化
    headers () {
      const signHeaders = {
        'body-string': '',
        'query-string': '',
        'x-nonce': `${utils.getRandomId()}`,
        'x-timestamp': `${new Date().getTime()}`
      }
      return {
        ...signHeaders,
        authorization: localStorage.getItem('authorization') || '',
        sign: generateSign(JSON.stringify(signHeaders)),
      }
    },
  },
  created () {
    this.getUserInfo()
  },
  methods: {
    handleSuccess(response) {
      this.daorushow= false;
      this.getUserInfo();
      this.$message.success('导入成功！')
    },
    /** 下载模板操作 */
    importTemplate() {
      // 绝对路径下的模版  在Java下的resource中
      location.href = 'http://localhost:8888/exam/%E7%94%A8%E6%88%B7%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx';
    },
    submitFileForm(){//确定上传
        this.$refs.uploadtm.submit();
    },
    handleError(err) {
      this.$message.error('导入失败：' + err.message)
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                      file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件！')
        return false
      }
      return true
    },
    //测试次数饼图
    drawPie1 () {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById('img2'))
      myChart.setOption({
        title: {
          text: '测试通过率',
          subtext: 'dashbord2',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c}次 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.pieData
        },
        series: [
          {
            name: '测试次数',
            type: 'pie',
            radius: '55%',
            data: this.pieData,
            roseType: 'angle',
            itemStyle: {
              normal: {
                shadowBlur: 200,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    },
    // 添加雷达图绘制方法
    drawRadar() {
      let myChart = this.$echarts.init(document.getElementById('leidatu'));

      // 计算百分比后的值
      let valuesInPercent = this.radarData.values.map(v => ((v / this.radarData.zf) * 100).toFixed(1));

      myChart.setOption({
        title: {
          text: '能力分析雷达图',
          x: 'center',
        },
        radar: {
          indicator: this.radarData.categories.map(category => ({
            name: category, // 确保每个属性名称正确显示
            max: 100, // 100% 为满值
            color: '#409EFF'
          })),
          shape: 'circle',
          splitNumber: 5, // 让刻度更均匀
          radius: '70%',
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            let tooltipContent = `<strong>${params.seriesName}</strong><br/>`;
            tooltipContent += `<span style="color:#909399;font-size:12px">根据题目权重和得分计算</span><br/>`;
            params.value.forEach((val, i) => {
              tooltipContent += `${this.radarData.categories[i]}: ${val}%<br/>`;
            });
            return tooltipContent;
          }
        },
        series: [{
          name: '能力得分',
          type: 'radar',
          data: [{
            value: valuesInPercent,
            name: '能力得分', // 这里确保 `name` 仍然正确
            areaStyle: {
              color: 'rgba(64,158,255,0.3)'
            },
            lineStyle: {
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF'
            }
          }]
        }]
      });
    },
    showUpdateNoticeDialog(row){
      this.kshfx = true;
      this.pieData = [];
      var that =this;
      // 添加雷达图
      statistic.huaxiang({ 'userId': row.id }).then((resp) => {
        console.log(resp)
        var list = resp.data;
        var df = 0;
        var categories = list.map(item => item.name);
        var values = list.map(item => item.value);
        var total = values.reduce((sum, val) => sum + val, 0);
        list.forEach(item => {
          df+=item.value;
        });
        this.radarData = {
          categories: categories,
          values: values,
          zf: total ||100
        }
        that.drawRadar();
      })
      // statistic.getExamPassRate2({ 'userId': row.id }).then((resp) => {
      //   console.log(resp)
      //   let examNames = resp.data[0].split(',')
      //   let examNumbers = resp.data[1].split(',')
      //   examNames.forEach((item, index) => {
      //     this.pieData.push({
      //       name: item,
      //       value: parseInt(examNumbers[index])
      //     })
      //   })
      //   this.drawPie1()
      // })
    },
    //获取用户信息
    getUserInfo () {
      user.getUserInfo2(this.queryInfo).then((resp) => {
        if (resp.code === 200) {
          this.userInfo = resp.data.data
          this.total = resp.data.total
          this.loading = false
        } else {
          this.$notify({
            title: 'Tips',
            message: '获取信息失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    //表格某一行被选中
    handleSelectionChange (val) {
      this.selectedInTable = val
    },
    //功能下拉框被选择
    selectChange (val) {
      //清空上一次的操作
      this.selected = ''
      //表格中所选中的用户的id
      let userIds = []
      this.selectedInTable.map(item => {
        userIds.push(item.id)
      })
      if (val === 'on') {//状态设置为正常
        user.handlerUser(1, { 'userIds': userIds.join(',') }).then((resp) => {
          if (resp.code === 200) {
            //删除成功后,回调更新用户数据
            this.getUserInfo()
            this.$notify({
              title: 'Tips',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: 'Tips',
              message: '操作失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      } else if (val === 'off') {//禁用用户
        user.handlerUser(2, { 'userIds': userIds.join(',') }).then((resp) => {
          if (resp.code === 200) {
            //删除成功后,回调更新用户数据
            this.getUserInfo()
            this.$notify({
              title: 'Tips',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: 'Tips',
              message: '操作失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      } else if (val === 'delete') {//删除用户
        user.handlerUser(3, { 'userIds': userIds.join(',') }).then((resp) => {
          if (resp.code === 200) {
            //删除成功后,回调更新用户数据
            this.getUserInfo()
            this.$notify({
              title: 'Tips',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: 'Tips',
              message: '操作失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }else if(val ==='edit'){

        // user.getUserByIds({'userIds':userIds.join(',') }).then((resp) => {
        //   if (resp.code === 200) {
        //     debugger;
        //   } else {
        //     this.$notify({
        //       title: 'Tips',
        //       message: '操作失败',
        //       type: 'error',
        //       duration: 2000
        //     })
        //   }
        // })
      }
    },
    getInfoEdit(row){

      this.addForm = {};
            this.addForm =row;
            this.addTableVisible = true
    },
    //分页插件的大小改变
    handleSizeChange (val) {
      this.queryInfo.pageSize = val
      this.getUserInfo()
    },
    //分页插件的页数
    handleCurrentChange (val) {
      this.queryInfo.pageNo = val
      this.getUserInfo()
    },
    //点击添加按钮
    showAddDialog () {
      this.addForm = {};
      this.addTableVisible = true
    },
    //添加用户
    addUser () {
      utils.validFormAndInvoke(this.$refs['addForm'], () => {
        user.addUser(this.addForm).then((resp) => {
          if (resp.code === 200) {
            this.getUserInfo()
            this.$notify({
              title: 'Tips',
              message: resp.message,
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: 'Tips',
              message: resp.message,
              type: 'error',
              duration: 2000
            })
          }
          this.addTableVisible = false
        })
      }, '请检查您所填写的信息是否有误')
    },
    editUser(){
      debugger;
      utils.validFormAndInvoke(this.$refs['addForm'], () => {
            this.addForm.password=null;
        user.editUser(this.addForm).then((resp) => {
          if (resp.code === 200) {
            this.getUserInfo()
            this.$notify({
              title: 'Tips',
              message: '成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: 'Tips',
              message: resp.message,
              type: 'error',
              duration: 2000
            })
          }
          this.addTableVisible = false
        })
      }, '请检查您所填写的信息是否有误')

    },
    //表单信息重置
    resetAddForm () {
      //清空表格数据
      this.$refs['addForm'].resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../assets/css/admin/userManage";
</style>
